import * as React from 'react';
import { partial } from 'lodash';
import { getAbsoluteStaticUrl } from 'utils/utils';
import AudioPlayer from 'components/common/AudioPlayer';
import VideoPlayer from 'components/common/VideoPlayer';
import CONFIG from 'constants/config';
import { Icon, Tooltip } from 'antd';
import './Media.scss';

function renderImage(attachment: any, onDestroy: any, imageStyle?: any) {
  if (!attachment || CONFIG.IMAGE_ACCEPT.indexOf(attachment.ext.toLowerCase()) === -1) {
    return null;
  }

  return (
    <div className="media-item" style={imageStyle}>
      <button onClick={partial(onDestroy, attachment.id)} className="ant-modal-close item-outsize">
        <Icon type="close-circle-o" style={{ fontSize: 20 }} />
      </button>
      <Tooltip title="点击查看原图">
        <a className="item-link" href={attachment.uri} target="_blank" rel="noopener noreferrer">
          <img style={{ width: '100%' }} src={getAbsoluteStaticUrl(attachment.uri)} />
        </a>
      </Tooltip>
    </div>
  );
}

function renderAudio(attachment: any, onDestroy: any, isTiny: boolean = true) {
  if (!attachment || CONFIG.AUDIO_ACCEPT.indexOf(attachment.ext.toLowerCase()) === -1) {
    return null;
  }

  return (
    <div>
      <div className="media-item">
        <button
          onClick={partial(onDestroy, attachment.id)}
          className="ant-modal-close item-outsize">
          <Icon type="close-circle-o" style={{ fontSize: 20 }} />
        </button>
        <AudioPlayer isTiny={isTiny} audioUri={attachment.uri} />
        {!isTiny && <span>{attachment.name}</span>}
      </div>
    </div>
  );
}

function renderVideo(attachment: any, onDestroy: any) {
  if (!attachment || CONFIG.VIDEO_ACCEPT.indexOf(attachment.ext.toLowerCase()) === -1) {
    return null;
  }

  return (
    <div className="media-item">
      <button onClick={partial(onDestroy, attachment.id)} className="ant-modal-close item-outsize">
        <Icon type="close-circle-o" style={{ fontSize: 20 }} />
      </button>
      <VideoPlayer isTiny={false} videoUri={attachment.uri} />
    </div>
  );
}

interface MediaProps {
  attachment: any;
  onDestroy: (id: number) => any;
  imageStyle?: any;
  isTiny?: boolean;
}
export default function Media(props: MediaProps) {
  const { attachment } = props;

  return (
    <div className="test-parser-option-item-media">
      {renderImage(attachment, props.onDestroy, props.imageStyle)}
      {renderAudio(attachment, props.onDestroy, props.isTiny)}
      {renderVideo(attachment, props.onDestroy)}
    </div>
  );
}
